package me.luraframework.auth.security;

import com.google.common.collect.ImmutableMap;
import lombok.RequiredArgsConstructor;
import me.luraframework.auth.security.dto.JwtUserDto;
import me.luraframework.auth.system.domain.User;
import me.luraframework.auth.system.repository.UserRepository;
import me.luraframework.commons.auth.UserContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Service
@RequiredArgsConstructor

public class AuthService {

    private final TokenProvider tokenProvider;
    private final AuthenticationManager authenticationManager;
    private final OnlineService onlineService;
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;


    public Map<String, Object> login(AuthUserDto authUserDto) {

        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(authUserDto.getUsername(), authUserDto.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        JwtUserDto jwtUser = (JwtUserDto) authentication.getPrincipal();
        UserContext uc = new UserContext();
        uc.setUserId(jwtUser.getUser().getId());
        uc.setUsername(jwtUser.getUsername());
        String token = tokenProvider.createToken(uc);
        onlineService.addUser(token, jwtUser);
        return ImmutableMap.of("token", token, "user", jwtUser);
    }

    public void logout(HttpServletRequest request) {
        String token = tokenProvider.getToken(request);
        onlineService.removeUser(token);
    }


    public void register(User resources) {
        resources.setPassword(passwordEncoder.encode(resources.getPassword()));
        userRepository.save(resources);
    }
}
